﻿Public Class Poliza_CxP
    Dim dtRes As DataTable
    Dim mostrado As Boolean = False
    Dim con As New Conexion_SQL(cst_SAE)

    Dim idDepto As Integer = 0
    Dim idIVA As Integer = 0

    Dim depto As String = ""
    Dim tiva As String = ""

    Private Sub btnBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuscar.Click
        dgvRes.DataSource = Nothing
        mostrado = False

        Dim cad As String = ""
        cad = "select P.CPROV, DOCTO, F.CVEFOLIO, D.NUM_REG AS DOC_REG, "
        cad += vbCrLf & "NOMBRE AS PROVEEDOR, RTRIM(POB) AS POBLACION, RTRIM(CLASIFIC) AS CLASE, "
        cad += vbCrLf & "case when DIAS_CRE=0 then 'Contado' else convert(char(3),DIAS_CRE) + 'días' end AS CREDITO, "
        cad += vbCrLf & "cast(SALDO as decimal(10,2)) AS SALDO, "
        cad += vbCrLf & "RTRIM(LTRIM(NO_FACTURA)) AS FACTURA, /*LTRIM(REFER) AS REFERENCIA, */"
        cad += vbCrLf & "convert(datetime, FECHA_APLI,103) AS INGRESO, "
        cad += vbCrLf & "convert(datetime, FECHA_VENC,103) AS VENCE, "
        cad += vbCrLf & "case when D.USUARIO=56 then 'Contraloria' else 'Caja' end as ORIGEN, "
        cad += vbCrLf & "case when IIVA=1 or IIVA is NULL then (case when (D.IMPORTE-IMPUESTO4+IMPFLETE+RETENCION)>0 then round(cast(IMPUESTO4/(D.IMPORTE-IMPUESTO4+IMPFLETE+RETENCION)*100 as real),0)/100 else 0 end) else IIVA end as PORC, "
        cad += vbCrLf & "case when DC.SUBTOTAL2=0 or DC.SUBTOTAL2 is null then D.IMPORTE-IMPUESTO4+IMPFLETE+RETENCION else DC.SUBTOTAL2 end AS SUBTOTAL, "
        cad += vbCrLf & "case when DC.SUBTOTAL2=0 or DC.SUBTOTAL2 is null THEN IMPUESTO4 else round(DC.SUBTOTAL2*(case when IIVA=1 then (case when (D.IMPORTE-IMPUESTO4+IMPFLETE+RETENCION)>0 then round(cast(IMPUESTO4/(D.IMPORTE-IMPUESTO4+IMPFLETE+RETENCION)*100 as real),0)/100 else 0 end) else IIVA end) ,2) end AS IVA, "
        cad += vbCrLf & "IMPFLETE AS IVA_RET, RETENCION AS ISR, "
        cad += vbCrLf & "round(case when DC.SUBTOTAL2=0 or DC.SUBTOTAL2 is null THEN D.IMPORTE else DC.SUBTOTAL2 + round(DC.SUBTOTAL2*(case when IIVA=1 then (case when (D.IMPORTE-IMPUESTO4+IMPFLETE+RETENCION)>0 then round(cast(IMPUESTO4/(D.IMPORTE-IMPUESTO4+IMPFLETE+RETENCION)*100 as real),0)/100 else 0 end) else IIVA end) ,2) end,2) AS TOTAL, "
        cad += vbCrLf & "X_OBSER AS OBSERVACIONES, DC.* "
        cad += vbCrLf & "from PROV01 P "
        cad += vbCrLf & "inner join PAGA01 D on P.CPROV=D.CPROV "
        cad += vbCrLf & "inner join FOLCXP01 F ON D.CVEFOLIO=F.CVEFOLIO "
        cad += vbCrLf & "left join OCXP01 O ON D.OBS_CXCCXP=O.NUM_REG "
        cad += vbCrLf & "left join Papalote.dbo.documentos DC ON D.NUM_REG=DC.NUM_REG "
        cad += vbCrLf & "where F.STATUS<>'C' and FECHA_APLI=convert(datetime,'" & Format(dtpFecha.Value, "yyyy-MM-dd") & "',111) AND TIPO_MOV=3 order by P.CPROV, DOC_REG, DC.T"

        dtRes = New DataTable
        con.ConnectDataBase(cst_SAE)
        con.OpenQueryIntoDataTable(dtRes, cad)
        con.DisconnectDataReader()
        con.DisconnectDataBase()

        If dtRes.Rows.Count = 0 Then
            MessageBox.Show("No se encontraron facturas para este día", "CxP", MessageBoxButtons.OK, MessageBoxIcon.Error)
            dgvRes.Visible = False
            gbDetalles.Visible = False

            btnGuardar.Visible = False
            btnPolizaN.Visible = False
            btnPolizaV.Visible = False
            btnExcel.Visible = False

            Exit Sub
        End If

        For Each col As DataColumn In dtRes.Columns
            col.ColumnName = col.ColumnName.Substring(0, 1).ToUpper & col.ColumnName.Substring(1).ToLower
        Next

        dtRes.Columns("Porc").ColumnName = "%"
        dtRes.Columns("Iva").ColumnName = "IVA"
        dtRes.Columns("Iva_ret").ColumnName = "IVA Ret"
        dtRes.Columns("Isr").ColumnName = "ISR"

        dtRes.Columns("Nuevar").ColumnName = "NuevaR"
        dtRes.Columns("Nuevab").ColumnName = "NuevaB"
        dtRes.Columns("Viejar").ColumnName = "ViejaR"
        dtRes.Columns("Viejab").ColumnName = "ViejaB"
        dtRes.Columns("Tipoiva").ColumnName = "TipoIVA"

        dtRes.Columns("IVA Ret").DefaultValue = 0
        dtRes.Columns("ISR").DefaultValue = 0
        dtRes.Columns("Saldo").DefaultValue = 0
        dtRes.Columns("NuevaR").DefaultValue = ""
        dtRes.Columns("NuevaB").DefaultValue = ""
        dtRes.Columns("ViejaR").DefaultValue = ""
        dtRes.Columns("ViejaB").DefaultValue = ""
        dtRes.Columns("Tipoiva").DefaultValue = 0
        dtRes.Columns("Departamento").DefaultValue = 0

        Dim dtCol As DataColumn

        dtCol = New DataColumn("_", GetType(Image))
        dtRes.Columns.Add(dtCol)
        dtRes.Columns("_").SetOrdinal(4)

        'dtCol = New DataColumn("Proveedor2", GetType(String))
        'dtRes.Columns.Add(dtCol)

        dtCol = New DataColumn("D", GetType(Image))
        dtRes.Columns.Add(dtCol)

        'For Each fila As DataRow In dtRes.Rows
        '    fila("Proveedor2") = fila("Proveedor")
        'Next


        dgvRes.DataSource = dtRes

        dgvRes.Columns("Saldo").DefaultCellStyle.Format = " $ ###,###,##0.00"
        dgvRes.Columns("Saldo").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        dgvRes.Columns("Subtotal").DefaultCellStyle.Format = " $ ###,###,##0.00"
        dgvRes.Columns("Subtotal").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        dgvRes.Columns("IVA Ret").DefaultCellStyle.Format = " $ ###,###,##0.00"
        dgvRes.Columns("IVA Ret").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        dgvRes.Columns("ISR").DefaultCellStyle.Format = " $ ###,###,##0.00"
        dgvRes.Columns("ISR").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        dgvRes.Columns("IVA").DefaultCellStyle.Format = " $ ###,###,##0.00"
        dgvRes.Columns("IVA").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        dgvRes.Columns("Total").DefaultCellStyle.Format = " $ ###,###,##0.00"
        dgvRes.Columns("Total").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
        dgvRes.Columns("%").DefaultCellStyle.Format = "#0%"
        dgvRes.Columns("%").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        dgvRes.Columns("Clase").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        dgvRes.Columns("Credito").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        dgvRes.Columns("Factura").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        dgvRes.Columns("Origen").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        dgvRes.Columns("Ingreso").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        dgvRes.Columns("Vence").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

        For Each fila As DataGridViewRow In dgvRes.Rows
            fila.Cells("Observaciones").Value = fila.Cells("Observaciones").Value.ToString.Split(" ").GetValue(0)
            If fila.Cells("Observaciones").Value.ToString.Trim.Length > 0 Then
                Dim Valor() As String = fila.Cells("Observaciones").Value.ToString.Split("/")
                If Valor.Length > 1 Then
                    fila.Cells("ViejaR").Value = IIf(fila.Cells("ViejaR").Value Is DBNull.Value, Crea_Cuenta(Valor(1)), fila.Cells("ViejaR").Value)
                    fila.Cells("ViejaR").Value = Crea_Cuenta(fila.Cells("ViejaR").Value)
                End If
                Dim subValor() As String = Valor(0).Split(",")
                If subValor.Length > 1 Then
                    fila.Cells("Departamento").Value = IIf(fila.Cells("Departamento").Value Is DBNull.Value, subValor(1), fila.Cells("Departamento").Value)
                End If
                fila.Cells("NuevaR").Value = IIf(fila.Cells("NuevaR").Value Is DBNull.Value, Crea_Cuenta(subValor(0)), fila.Cells("NuevaR").Value)
                fila.Cells("NuevaR").Value = Crea_Cuenta(fila.Cells("NuevaR").Value)
            End If

            If fila.Cells("NuevaR").Value.ToString.Trim.Length = 0 OrElse fila.Cells("NuevaB").Value.ToString.Trim.Length = 0 OrElse fila.Cells("Departamento").Value = 0 OrElse fila.Cells("TipoIVA").Value = 0 OrElse fila.Cells("Concepto").Value.ToString.Trim.Length = 0 Then
                fila.Cells("_").Value = My.Resources.lightbulb
            Else
                fila.Cells("_").Value = My.Resources.check
            End If
            fila.Cells("Num_reg").Value = fila.Cells("Doc_reg").Value

            'fila.Cells("Proveedor2").Value = fila.Cells("Proveedor").Value

            If Not fila.Cells("T").Value Is DBNull.Value Then
                Select Case fila.Cells("T").Value
                    Case "N"
                        fila.Cells("D").Value = My.Resources.communication
                    Case "D"
                        fila.Cells("D").Value = My.Resources.plus
                    Case "S"
                        fila.Cells("D").Value = My.Resources.busy
                        fila.Cells("Proveedor").Value = "   - " & fila.Cells("Concepto").Value
                        fila.Cells("Clase").Value = "-"
                        fila.Cells("Credito").Value = "-"
                        fila.Cells("Poblacion").Value = "-"
                End Select
            Else
                fila.Cells("T").Value = "N"
                fila.Cells("D").Value = My.Resources.communication
            End If

        Next

        dgvRes.Columns("Cprov").Visible = False
        dgvRes.Columns("Docto").Visible = False
        dgvRes.Columns("Cvefolio").Visible = False
        dgvRes.Columns("Doc_reg").Visible = False
        dgvRes.Columns("Observaciones").Visible = False
        dgvRes.Columns("Ingreso").Visible = False

        dgvRes.Columns("Num_reg").Visible = False
        dgvRes.Columns("NuevaR").Visible = False
        dgvRes.Columns("NuevaB").Visible = False
        dgvRes.Columns("ViejaR").Visible = False
        dgvRes.Columns("ViejaB").Visible = False
        dgvRes.Columns("Departamento").Visible = False
        dgvRes.Columns("TipoIVA").Visible = False
        dgvRes.Columns("Concepto").Visible = False
        dgvRes.Columns("T").Visible = False
        dgvRes.Columns("Subtotal2").Visible = False
        dgvRes.Columns("Id").Visible = False
        dgvRes.Columns("Iiva").Visible = False
        dgvRes.Columns("Linea").Visible = False

        dgvRes.Columns("NuevaR").DefaultCellStyle.NullValue = ""
        dgvRes.Columns("NuevaB").DefaultCellStyle.NullValue = ""
        dgvRes.Columns("ViejaR").DefaultCellStyle.NullValue = ""
        dgvRes.Columns("ViejaB").DefaultCellStyle.NullValue = ""
        dgvRes.Columns("Departamento").DefaultCellStyle.NullValue = "0"
        dgvRes.Columns("TipoIVA").DefaultCellStyle.NullValue = "0"
        dgvRes.Columns("Concepto").DefaultCellStyle.NullValue = ""

        For Each col As DataGridViewColumn In dgvRes.Columns
            col.HeaderCell.Style.Alignment = col.DefaultCellStyle.Alignment
        Next

        mostrado = True
        dgvRes.Visible = True
        gbDetalles.Visible = False

        dgvRes.SelectedRows(0).Selected = False

        valida()
    End Sub

    Private Sub dgvRes_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgvRes.SelectionChanged
        Muestra_Detalles()
    End Sub

    Private Sub Muestra_Detalles()
        If dgvRes.SelectedRows.Count > 0 And mostrado = True Then
            Dim fila As DataGridViewRow = dgvRes.SelectedRows(0)
            If Not (fila.Cells("T").Value Is DBNull.Value) AndAlso fila.Cells("T").Value = "S" Or fila.Cells("T").Value = "N" Then
                gbDetalles.Visible = True
            Else
                gbDetalles.Visible = False
            End If

            If fila.Cells("NuevaR").Value.ToString.Trim.Length = 0 OrElse fila.Cells("NuevaB").Value.ToString.Trim.Length = 0 OrElse fila.Cells("Departamento").Value = 0 OrElse fila.Cells("TipoIVA").Value = 0 OrElse fila.Cells("Concepto").Value.ToString.Trim.Length = 0 Then
                pbStatus.Image = My.Resources.lightbulb
            Else
                pbStatus.Image = My.Resources.check
            End If

            pbStatus.Visible = True

            lbFactura.Text = fila.Cells("Factura").Value
            lbFecha.Text = fila.Cells("Ingreso").Value
            lbVence.Text = fila.Cells("Vence").Value
            lbOrigen.Text = fila.Cells("Origen").Value

            If fila.Cells("T").Value = "N" Then
                lbProveedor.Text = fila.Cells("Proveedor").Value
                lbPoblacion.Text = fila.Cells("Poblacion").Value
                lbClase.Text = fila.Cells("Clase").Value
                lbCredito.Text = fila.Cells("Credito").Value
                lbSaldo.Text = Format(fila.Cells("Saldo").Value, "$ ###,###,##0.00")
            ElseIf fila.Cells("T").Value = "S" Then
                Dim DocReg As Integer = fila.Cells("Doc_reg").Value
                Dim fila2 As DataRow = CType(dtRes.Select("T='D' and Doc_Reg=" & DocReg).GetValue(0), DataRow)
                lbProveedor.Text = fila2("Proveedor")
                lbPoblacion.Text = fila2("Poblacion")
                lbClase.Text = fila2("Clase")
                lbCredito.Text = fila2("Credito")
                lbSaldo.Text = Format(fila2("Saldo"), "$ ###,###,##0.00")
            End If



            lbSubtotal.Text = Format(IIf(fila.Cells("Subtotal").Value Is DBNull.Value, 0, fila.Cells("Subtotal").Value), "$ ###,###,##0.00")
            lbPiva.Text = Format(IIf(fila.Cells("%").Value Is DBNull.Value, 0, fila.Cells("%").Value), "#0%")
            lbIva.Text = Format(IIf(fila.Cells("IVA").Value Is DBNull.Value, 0, fila.Cells("IVA").Value), "$ ###,###,##0.00")
            lbTotal.Text = Format(IIf(fila.Cells("Total").Value Is DBNull.Value, 0, fila.Cells("Total").Value), "$ ###,###,##0.00")
            lbIsr.Text = Format(IIf(fila.Cells("ISR").Value Is DBNull.Value, 0, fila.Cells("ISR").Value), "$ ###,###,##0.00")
            lbIvaRet.Text = Format(IIf(fila.Cells("IVA Ret").Value Is DBNull.Value, 0, fila.Cells("IVA Ret").Value), "$ ###,###,##0.00")

            lbCtaNuevaR.Text = IIf(fila.Cells("NuevaR").Value Is DBNull.Value, "", fila.Cells("NuevaR").Value)
            txtCtaNuevaR.Text = IIf(fila.Cells("NuevaR").Value Is DBNull.Value, "", fila.Cells("NuevaR").Value)
            lbCtaViejaR.Text = IIf(fila.Cells("ViejaR").Value Is DBNull.Value, "", fila.Cells("ViejaR").Value)
            txtCtaViejaR.Text = IIf(fila.Cells("ViejaR").Value Is DBNull.Value, "", fila.Cells("ViejaR").Value)

            lbCtaNuevaB.Text = IIf(fila.Cells("NuevaB").Value Is DBNull.Value, "", fila.Cells("NuevaB").Value)
            txtCtaNuevaB.Text = IIf(fila.Cells("NuevaB").Value Is DBNull.Value, "", fila.Cells("NuevaB").Value)
            lbCtaViejaB.Text = IIf(fila.Cells("ViejaB").Value Is DBNull.Value, "", fila.Cells("ViejaB").Value)
            txtCtaViejaB.Text = IIf(fila.Cells("ViejaB").Value Is DBNull.Value, "", fila.Cells("ViejaB").Value)
            lbConcepto.Text = IIf(fila.Cells("Concepto").Value Is DBNull.Value, "", fila.Cells("Concepto").Value)
            txtConcepto.Text = IIf(fila.Cells("Concepto").Value Is DBNull.Value, "", fila.Cells("Concepto").Value)

            Crea_Cuenta(lbCtaNuevaR.Text)
            Crea_Cuenta(txtCtaNuevaR.Text)
            Crea_Cuenta(lbCtaViejaR.Text)
            Crea_Cuenta(txtCtaViejaR.Text)

            Crea_Cuenta(lbCtaNuevaB.Text)
            Crea_Cuenta(txtCtaNuevaB.Text)
            Crea_Cuenta(lbCtaViejaB.Text)
            Crea_Cuenta(txtCtaViejaB.Text)

            idDepto = IIf(fila.Cells("Departamento").Value Is DBNull.Value, 0, fila.Cells("Departamento").Value)
            depto = con.QueryGetFieldTmpCnn("select cast(id_departamento as char(2)) + ' - ' + departamento from departamentos where id_departamento=" & idDepto, cst_Papalote)
            lbDepto.Text = depto
            txtDepto.Text = depto

            idIVA = IIf(fila.Cells("TipoIVA").Value Is DBNull.Value, 0, fila.Cells("TipoIVA").Value)
            tiva = con.QueryGetFieldTmpCnn("select descripcion from cuenta_iva where id_cuenta_iva=" & idIVA, cst_Papalote)
            lbTipoIva.Text = tiva
            txtTipoIva.Text = tiva

            txtCtaNuevaR.Visible = False
            txtCtaViejaR.Visible = False
            txtCtaNuevaB.Visible = False
            txtCtaViejaB.Visible = False
            txtConcepto.Visible = False

            txtDepto.Visible = False
            txtTipoIva.Visible = False

            lbCtaNuevaR.Visible = True
            lbCtaViejaR.Visible = True
            lbCtaNuevaB.Visible = True
            lbCtaViejaB.Visible = True
            lbConcepto.Visible = True

            lbDepto.Visible = True
            lbTipoIva.Visible = True

            valida()

            dgvRes.Focus()
        End If
    End Sub

    Private Sub dgvRes_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvRes.KeyDown
        If e.KeyCode = Keys.Delete Or e.KeyCode = Keys.Space Then
            lbCtaNuevaR.Visible = False
            lbCtaViejaR.Visible = False
            lbCtaNuevaB.Visible = False
            lbCtaViejaB.Visible = False
            lbDepto.Visible = False
            lbTipoIva.Visible = False
            lbConcepto.Visible = False

            txtCtaNuevaR.Visible = True
            txtCtaViejaR.Visible = True
            txtCtaNuevaB.Visible = True
            txtCtaViejaB.Visible = True
            txtDepto.Visible = True
            txtTipoIva.Visible = True
            txtConcepto.Visible = True

            btnActualizar.Visible = True

            txtConcepto.Focus()
        End If
    End Sub

    Private Sub txtConcepto_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtConcepto.KeyDown
        If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
            txtCtaNuevaR.Focus()
        End If
        If e.KeyCode = Keys.F1 Then
            txtConcepto.Text = lbProveedor.Text
        End If
    End Sub

    Private Sub txtCtaNuevaR_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCtaNuevaR.KeyDown
        If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
            txtCtaNuevaR.Text = Crea_Cuenta(txtCtaNuevaR.Text)
            txtCtaViejaR.Focus()
        End If
    End Sub

    Private Sub txtCtaViejaR_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCtaViejaR.KeyDown
        If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
            txtCtaViejaR.Text = Crea_Cuenta(txtCtaViejaR.Text)
            txtCtaNuevaB.Focus()
        End If
    End Sub

    Private Sub txtCtaNuevaB_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCtaNuevaB.KeyDown
        If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
            txtCtaNuevaB.Text = Crea_Cuenta(txtCtaNuevaB.Text)
            txtCtaViejaB.Focus()
        End If
    End Sub

    Private Sub txtCtaViejaB_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtCtaViejaB.KeyDown
        If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
            txtCtaViejaB.Text = Crea_Cuenta(txtCtaViejaB.Text)
            txtDepto.Focus()
        End If
    End Sub

    Private Sub Cuentas_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCtaNuevaB.KeyPress, txtCtaNuevaR.KeyPress, txtCtaViejaB.KeyPress, txtCtaViejaR.KeyPress
        If Char.IsDigit(e.KeyChar) Or e.KeyChar = "-"c Or e.KeyChar = ""c Then
            e.Handled = False
        Else
            e.Handled = True
        End If
    End Sub

    Private Sub txtDepto_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtDepto.KeyDown
        If e.KeyCode = Keys.Space Or e.KeyCode = Keys.Delete Then
            Dim cat As New Catalogo
            'cat.Location = New Point(txtDepto.Location.X, txtDepto.Location.Y)
            cat.Text = "Departamentos"
            idDepto = cat.Mostrar("select id_departamento, cast(id_departamento as char(2)) + ' - ' + departamento from departamentos order by id_departamento", cst_Papalote, idDepto)
            depto = con.QueryGetFieldTmpCnn("select cast(id_departamento as char(2)) + ' - ' + departamento from departamentos where id_departamento=" & idDepto, cst_Papalote)
            lbDepto.Text = depto
            txtDepto.Text = depto
        ElseIf e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Return Then
            txtTipoIva.Focus()
        Else
            e.Handled = True
        End If
    End Sub

    Private Sub txtTipoIva_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTipoIva.KeyDown
        If e.KeyCode = Keys.Space Or e.KeyCode = Keys.Delete Then
            Dim cat As New Catalogo
            'cat.Location = New Point(txtDepto.Location.X, txtDepto.Location.Y)
            cat.Text = "Tipo IVA"
            idIVA = cat.Mostrar("select id_cuenta_iva, descripcion from cuenta_iva where tipo_iva=1 and pasivo=1 order by descripcion", cst_Papalote, idIVA)
            tiva = con.QueryGetFieldTmpCnn("select descripcion from cuenta_iva where id_cuenta_iva=" & idIVA, cst_Papalote)
            lbTipoIva.Text = tiva
            txtTipoIva.Text = tiva
        ElseIf e.KeyCode = Keys.Enter Or e.KeyCode = Keys.Return Then
            btnActualizar.Focus()
        Else
            e.Handled = True
        End If
    End Sub

    Private Sub Tipos_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTipoIva.KeyPress, txtDepto.KeyPress
        e.Handled = True
    End Sub

    Private Sub btnActualizar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnActualizar.Click
        dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("NuevaR").Value = txtCtaNuevaR.Text
        dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("NuevaB").Value = txtCtaNuevaB.Text
        dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("ViejaR").Value = txtCtaViejaR.Text
        dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("ViejaB").Value = txtCtaViejaB.Text
        dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("Concepto").Value = txtConcepto.Text

        dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("Departamento").Value = idDepto
        dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("TipoIVA").Value = idIVA

        If dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("NuevaR").Value.ToString.Trim.Length = 0 OrElse dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("NuevaB").Value.ToString.Trim.Length = 0 OrElse dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("Departamento").Value = 0 OrElse dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("TipoIVA").Value = 0 OrElse dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("NuevaR").Value.ToString.StartsWith("000") OrElse dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("NuevaB").Value.ToString.StartsWith("000") OrElse dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("Concepto").Value.ToString.Trim.Length = 0 Then
            dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("_").Value = My.Resources.lightbulb
        Else
            dgvRes.Rows(dgvRes.SelectedRows(0).Index).Cells("_").Value = My.Resources.check
        End If

        btnActualizar.Visible = False
        Muestra_Detalles()
    End Sub

    Private Sub valida()
        Dim validos As Integer = 0
        For Each fila As DataGridViewRow In dgvRes.Rows
            If fila.Cells("T").Value = "N" Or fila.Cells("T").Value = "S" Then
                Dim vTipoIVA As Integer = IIf(fila.Cells("TipoIVA").Value Is DBNull.Value, 0, fila.Cells("TipoIVA").Value)
                Dim vDepartamento As Integer = IIf(fila.Cells("Departamento").Value Is DBNull.Value, 0, fila.Cells("Departamento").Value)
                Dim vNuevaR As String = IIf(fila.Cells("NuevaR").Value Is DBNull.Value, "", fila.Cells("NuevaR").Value)
                Dim vNuevaB As String = IIf(fila.Cells("NuevaB").Value Is DBNull.Value, "", fila.Cells("NuevaB").Value)
                Dim Concepto As String = IIf(fila.Cells("Concepto").Value Is DBNull.Value, "", fila.Cells("Concepto").Value)

                If vTipoIVA > 0 AndAlso vDepartamento > 0 AndAlso Not (vNuevaR.StartsWith("000")) AndAlso Not (vNuevaB.StartsWith("000")) AndAlso Concepto.Trim.Length > 0 Then
                    validos += 1
                End If
            ElseIf fila.Cells("T").Value = "D" Then
                Dim DocReg As Integer = fila.Cells("Doc_reg").Value
                Dim importe As Double = 0
                Dim iva As Double = 0
                For Each fila2 As DataGridViewRow In dgvRes.Rows
                    If fila2.Cells("Doc_reg").Value = DocReg AndAlso fila2.Cells("T").Value = "S" Then
                        importe += fila2.Cells("Total").Value
                        iva += fila2.Cells("IVA").Value
                    End If
                Next
                If FormatCurrency(importe, 2) = FormatCurrency(fila.Cells("Total").Value, 2) AndAlso FormatCurrency(iva, 2) = FormatCurrency(fila.Cells("IVA").Value, 2) Then
                    validos += 1
                    fila.Cells("_").Value = My.Resources.check
                Else
                    fila.Cells("_").Value = My.Resources.lightbulb
                End If
            End If
        Next

        If validos = dgvRes.Rows.Count Then
            btnGuardar.Visible = True
            btnPolizaN.Visible = True
            btnPolizaV.Visible = True
            btnExcel.Visible = True
        Else
            btnGuardar.Visible = False
            btnPolizaN.Visible = False
            btnPolizaV.Visible = False
            btnExcel.Visible = False
        End If
    End Sub

    Private Sub btnGuardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGuardar.Click
        con.ConnectDataBase(cst_Papalote)

        Dim cad As String = ""
        For Each fila As DataGridViewRow In dgvRes.Rows
            cad = "DELETE FROM documentos WHERE NUM_REG=" & fila.Cells("Num_reg").Value
            con.ExecuteSQL(cad)
        Next

        For Each fila As DataGridViewRow In dgvRes.Rows
            If fila.Cells("T").Value = "N" Or fila.Cells("T").Value = "S" Then
                Dim stot As Double = IIf(fila.Cells("Subtotal2").Value Is DBNull.Value, 0, fila.Cells("Subtotal2").Value)
                Dim iiva As Double = IIf(fila.Cells("iiva").Value Is DBNull.Value, 1, fila.Cells("iiva").Value)
                cad = "INSERT INTO documentos(NUM_REG,NUEVAR,DEPARTAMENTO,VIEJAR,NUEVAB,VIEJAB,TIPOIVA,CONCEPTO,T,SUBTOTAL2,IIVA) "
                cad += "VALUES(" & fila.Cells("Num_reg").Value & ", "
                cad += "'" & Crea_Cuenta(fila.Cells("NuevaR").Value) & "'," & fila.Cells("Departamento").Value & ",'" & Crea_Cuenta(fila.Cells("ViejaR").Value) & "','" & Crea_Cuenta(fila.Cells("NuevaB").Value) & "','" & Crea_Cuenta(fila.Cells("ViejaB").Value) & "'," & fila.Cells("TipoIVA").Value & ",'" & fila.Cells("Concepto").Value & "','" & fila.Cells("T").Value & "'," & stot & "," & iiva & ")"
            Else
                cad = "INSERT INTO documentos(NUM_REG,T) "
                cad += "VALUES(" & fila.Cells("Num_reg").Value & ", 'D')"
            End If
            con.ExecuteSQL(cad)
        Next
        con.DisconnectDataBase()

        MessageBox.Show("Documentos guardados con éxito", "Cuentas por pagar", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    Private Sub dgvRes_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvRes.CellContentClick
        If e.ColumnIndex = dgvRes.Columns.Count - 1 Then
            Dim orden As Integer = e.RowIndex
            If dgvRes.Rows(e.RowIndex).Cells("T").Value = "N" Or dgvRes.Rows(e.RowIndex).Cells("T").Value = "D" Then
                Dim fila As DataRow
                fila = dtRes.NewRow
                Dim ag As New SubFactura
                Dim vConcepto As String = ""
                Dim vTotal As Double = 0
                Dim vIva As Double = IIf(dgvRes.Rows(e.RowIndex).Cells("Iiva").Value Is DBNull.Value OrElse dgvRes.Rows(e.RowIndex).Cells("Iiva").Value = 1, dgvRes.Rows(e.RowIndex).Cells("%").Value, dgvRes.Rows(e.RowIndex).Cells("Iiva").Value)

                If ag.mostrar(dgvRes.Rows(e.RowIndex).Cells("Factura").Value, vConcepto, vTotal, vIva) Then
                    dgvRes.Rows(e.RowIndex).Cells("T").Value = "D"
                    dgvRes.Rows(e.RowIndex).Cells("_").Value = My.Resources.lightbulb
                    dgvRes.Rows(e.RowIndex).Cells("D").Value = My.Resources.plus

                    fila("Concepto") = vConcepto
                    fila("Subtotal") = vTotal
                    fila("Subtotal2") = vTotal

                    fila("IVA") = vTotal * vIva
                    fila("Iiva") = vIva
                    fila("%") = vIva

                    fila("Poblacion") = "-"
                    fila("Clase") = "-"
                    fila("Credito") = "-"


                    fila("Total") = fila("Subtotal") + fila("IVA")

                    fila("Proveedor") = "   - " & fila("Concepto")
                    fila("T") = "S"
                    fila("_") = My.Resources.lightbulb
                    fila("D") = My.Resources.busy
                    For Each col As DataColumn In dtRes.Columns
                        If fila(col) Is DBNull.Value Then
                            fila(col) = dtRes.Rows(orden)(col)
                        End If
                    Next
                    dtRes.Rows.InsertAt(fila, orden + 1)
                    gbDetalles.Visible = False
                End If
            Else
                Dim DocReg As Integer = dtRes.Rows(orden)("Doc_reg")
                dtRes.Rows.RemoveAt(orden)

                Dim filas As DataRow() = dtRes.Select("Doc_reg=" & DocReg)
                If filas.Count = 1 Then
                    filas(0)("T") = "N"
                    filas(0)("_") = My.Resources.lightbulb
                    filas(0)("D") = My.Resources.communication
                End If
            End If
            valida()
        End If
    End Sub

    Private Sub btnPolizaV_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPolizaV.Click
        Genera_Poliza(Poliza_preview.Tipo_Poliza.Vieja)
    End Sub

    Private Sub btnPolizaN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPolizaN.Click
        Genera_Poliza(Poliza_preview.Tipo_Poliza.Nueva)
    End Sub

    Public Sub Genera_Poliza(ByVal Tipo As Poliza_preview.Tipo_Poliza)
        Dim col As String = ""
        Dim Depto As Integer = 0

        If Tipo = Poliza_preview.Tipo_Poliza.Nueva Then
            col = "Nueva"
        Else
            col = "Vieja"
        End If


        Dim PP As New Poliza_preview
        For Each fila As DataGridViewRow In dgvRes.Rows
            If fila.Cells("T").Value = "N" Or fila.Cells("T").Value = "S" Then

                Dim concepto As String = ""
                If fila.Cells("T").Value = "N" Then
                    concepto = fila.Cells("Proveedor").Value
                Else
                    Dim DocReg As Integer = fila.Cells("Doc_reg").Value
                    Dim fila2 As DataRow = CType(dtRes.Select("T='D' and Doc_Reg=" & DocReg).GetValue(0), DataRow)
                    concepto = fila2("Proveedor")
                End If

                concepto += " / " & fila.Cells("Concepto").Value

                If Tipo = Poliza_preview.Tipo_Poliza.Nueva Then
                    Depto = fila.Cells("Departamento").Value
                Else
                    Depto = 0
                End If

                Dim Doc As New Poliza_preview.Documento(concepto, concepto, fila.Cells("Subtotal").Value, fila.Cells("IVA").Value, fila.Cells("IVA Ret").Value, fila.Cells("ISR").Value, Crea_Cuenta(fila.Cells(col & "R").Value), Crea_Cuenta(fila.Cells(col & "B").Value), Depto, fila.Cells("Tipoiva").Value, Tipo)
                PP.Agrega_Doc(Doc)
            End If
        Next
        PP.Mostrar(dtpFecha.Value)
    End Sub

    Private Sub btnExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExcel.Click
        Dim sfd As New SaveFileDialog
        sfd.Filter = "Excel (*.xls)|*.xls"
        If sfd.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim dtExcel As New DataTable
            dtExcel = dtRes.Clone
            For Each fila As DataRow In dtRes.Rows
                dtExcel.ImportRow(fila)
            Next

            dtExcel.Columns.Remove("Cprov")
            dtExcel.Columns.Remove("Docto")
            dtExcel.Columns.Remove("Cvefolio")
            dtExcel.Columns.Remove("Doc_reg")
            dtExcel.Columns.Remove("Observaciones")
            dtExcel.Columns.Remove("Num_reg")
            dtExcel.Columns.Remove("NuevaR")
            dtExcel.Columns.Remove("NuevaB")
            dtExcel.Columns.Remove("ViejaR")
            dtExcel.Columns.Remove("ViejaB")
            dtExcel.Columns.Remove("Departamento")
            dtExcel.Columns.Remove("TipoIVA")
            dtExcel.Columns.Remove("Concepto")
            dtExcel.Columns.Remove("T")
            dtExcel.Columns.Remove("Subtotal2")
            dtExcel.Columns.Remove("_")
            dtExcel.Columns.Remove("D")

            Dim dsExcel As New DataSet
            dsExcel.Tables.Add(dtExcel)

            Dim EE As New ExporImporExcel
            EE.exportExcelXML(dsExcel, sfd.FileName)

            MessageBox.Show("Documento creado con éxito", "CxP", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
End Class
